package com.lixinlei.mc.api.sms.cat;

import com.alibaba.fastjson.JSON;
import org.smslib.*;
import org.smslib.modem.SerialModemGateway;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.Map;

@Service
public class SmsCatSendService {

    @PostConstruct
    public void init(){
        SmsCatSendService.OutboundNotification outboundNotification
                = new SmsCatSendService.OutboundNotification();

        SerialModemGateway gateway = new SerialModemGateway(
                "modem.com3",
                "COM3",
                9600,
                "null",
                "null");
        gateway.setInbound(false);
        gateway.setOutbound(true);
        gateway.setSimPin("0000");

        try {
            org.smslib.Service.getInstance().setOutboundMessageNotification(outboundNotification);
            org.smslib.Service.getInstance().addGateway(gateway);  //将网关添加到短信猫服务中
            org.smslib.Service.getInstance().startService();   //启动服务，进入短信发送就绪状态
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        System.out.println("SMS CAT Service Started...");
    }

    public String send(String phone, String content) {
        OutboundMessage msg = new OutboundMessage(phone, content);
        try {
            msg.setEncoding(Message.MessageEncodings.ENCUCS2);
            org.smslib.Service.getInstance().sendMessage(msg);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("Cause", e.getCause());
            result.put("LocalizedMessage", e.getLocalizedMessage());
            result.put("Message", e.getMessage());
            result.put("getStackTrace", e.getStackTrace());
            return JSON.toJSONString(result);
        }
        return JSON.toJSONString(msg);
    }

    @PreDestroy
    public void destroy(){
        try {
            org.smslib.Service.getInstance().stopService();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println("SMS CAT Service Stopped.");
    }

    public class OutboundNotification implements IOutboundMessageNotification {
        @Override
        public void process(AGateway aGateway, OutboundMessage outboundMessage) {
            System.out.println("OutboundNotification aGateway.getGatewayId(): " + aGateway.getGatewayId());
            System.out.println("OutboundNotification outboundMessage:" + outboundMessage);
        }
    }

}
